import { Toast } from 'antd-mobile';
import axios, { AxiosRequestConfig } from 'axios';

import { getToken } from './common';

function search2obj(search: string) {
  if (search[0] === '?') {
    search = search.substring(1);
  }
  const arr = search.split('&').filter(Boolean);

  const obj: Record<string, string> = {};
  arr.forEach((t) => {
    const [key, value] = t.split('=');
    if (['tag', 'landingpage', 'unit', 'bd_vid', 'qhclickid'].indexOf(key) > -1) {
      let mykey = 'x-' + key;
      if (key == 'bd_vid') {
        mykey = 'x-' + 'bd';
      }
      obj[mykey] = decodeURIComponent(value);
    }
  });
  return obj;
}

const heardObj = search2obj(location.search);

// aiart-api.ruiyanshijie.com
const instance = axios.create({
  timeout: 100000, //默认超时时间
  withCredentials: true, //跨域请求，允许保存cookie
  validateStatus: function (status) {
    return status >= 200 && status <= 500;
  },
});
const host = location.hostname;
let apiHost = '';
if (host === 'aiart-dev.ruiyanshijie.com') {
  apiHost = 'aiart-dev-api.ruiyanshijie.com';
} else {
  apiHost = location.hostname.replace('aiart', 'aiart-api');
}

host.split('.');
function request<T>({
  hiddenMsg,
  ...config
}: AxiosRequestConfig<unknown> & { hiddenMsg?: boolean } = {}): Promise<T> {
  config.url = import.meta.env.DEV
    ? '/api' + config.url
    : location.protocol + '//' + apiHost + config.url;
  if (!config.headers) {
    config.headers;
  }
  config.headers = Object.assign({}, config.headers, heardObj);

  config.headers.Authorization = 'Bearer ' + getToken();

  return new Promise((resolve, reject) => {
    return instance(config)
      .then((response) => {
        if (response.data.success) {
          resolve(response.data.data);
        } else {
          if (!hiddenMsg) {
            if (response.data.error_code === 10002) {
              Toast.show('请登录');
            } else {
              Toast.show(response.data.message);
            }
          }

          reject(response.data);
        }
      })
      .catch((e) => {
        console.log(e);

        reject(e);
      });
  });
}

const get = <T = unknown>(
  url: string,
  params: AxiosRequestConfig['params'] = {},
  opts: AxiosRequestConfig<unknown> & { hiddenMsg?: boolean } = {}
): Promise<T> => request({ url, params, ...opts, method: 'GET' });

const post = <T = unknown>(
  url: string,
  data: AxiosRequestConfig['data'] = {},
  opts: AxiosRequestConfig<unknown> & { hiddenMsg?: boolean } = {}
): Promise<T> => request({ url, data, ...opts, method: 'POST' });

const req = {
  get,
  post,
};

export default req;
